package com.open.capacity.tenant.config;

import com.open.capacity.tenant.dao.AdminMapper;
import com.open.capacity.tenant.dao.entity.Admin;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;

/**
 * 自定义身份认证
 * @program: tenant-server
 * @author: GuoGaoJu
 * @create: 2023-04-06
 **/
@Slf4j
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private AdminMapper adminMapper;

    @Resource
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    /**
     * 用户登录时，会自动进入此方法，判断用户名是否存在，并校验密码
     * @param username 用户名
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //1.查询用户是否存在
        Admin userEntity = adminMapper.findByUsername(username);
        if (userEntity == null){
            log.info("用户不存在！");
            return null;
        }

        //2.因为超管账号体系和租户是隔离开的，且业务也是隔离的，所以超管账号直接默认管理员权限
        ArrayList<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        grantedAuthorities.add(new SimpleGrantedAuthority("admin"));

        //spring security5.0后密码需要加密，否则报错
        userEntity.setPassword(bCryptPasswordEncoder.encode(userEntity.getPassword()));
        System.out.println("------------------------"+userEntity.getPassword()+"------------------------");
        userEntity.setAuthorities(grantedAuthorities);
        return userEntity;
    }
}